import { defineStore } from 'pinia'
import { ref, reactive, computed } from 'vue'
import request from '@/utils/request'
import { ElMessage } from 'element-plus'
import { useUserStore } from './user'
import { pinia } from '@/main'

export const useStudentStore = defineStore('student', () => {
    // 初始化用户Store
    const userStore = useUserStore(pinia)

    // 核心响应式状态 - 确保所有数据都是响应式的
    const studentList = ref([]) // 学生列表 - 关键响应式数组
    const total = ref(0) // 总条数
    const currentPage = ref(1) // 当前页码
    const pageSize = ref(10) // 每页条数
    const loading = ref(false) // 加载状态
    const searchName = ref('') // 搜索关键词
    const campusList = ref([]) // 校区列表

    // 表单数据
    const formData = reactive({
        id: null,
        username: '',
        realName: '',
        gender: 'male',
        phone: '',
        email: '',
        age: null,
        campusId: '',
        campusName: ''
    })

    // 权限判断
    const isSuperAdmin = computed(() =>
        userStore.user?.userType === 'admin' && userStore.user?.campus?.id === '1'
    )

    // 获取学生列表 - 带完整调试日志
    const fetchStudentList = async () => {
        loading.value = true
        try {
            console.log('===== 开始获取学生列表 =====')

            // 构建查询参数
            const queryParams = {
                page: currentPage.value,
                size: pageSize.value
            }

            if (searchName.value.trim()) {
                queryParams.name = searchName.value.trim()
                console.log('搜索参数:', queryParams.name)
            }

            // 普通管理员自动添加校区筛选
            if (!isSuperAdmin.value && userStore.user?.campus?.id) {
                queryParams.campusId = userStore.user.campus.id
                console.log('自动筛选校区ID:', queryParams.campusId)
            }

            // 发送请求
            let response
            let apiUrl = '/user/students'

            if (!isSuperAdmin.value && userStore.user?.campus?.id) {
                apiUrl = '/user/students/campus'
            }

            console.log('请求API:', apiUrl)
            console.log('请求参数:', queryParams)

            response = await request.get(apiUrl, queryParams)

            // 打印完整响应
            console.log('API完整响应:', response)

            // 处理返回数据
            const rawData = response.data || []
            console.log('原始学生数据:', rawData)
            console.log('原始数据长度:', rawData.length)

            // 存入响应式数组
            studentList.value = rawData
            console.log('存入studentList后的数据:', studentList.value)
            console.log('studentList长度:', studentList.value.length)

            // 处理总数
            total.value = response.total !== undefined ? response.total : studentList.value.length
            console.log('总条数:', total.value)

            console.log('===== 获取学生列表完成 =====')
            return studentList.value
        } catch (error) {
            console.error('===== 获取学生列表失败 =====', error)
            studentList.value = []
            total.value = 0
            return []
        } finally {
            loading.value = false
        }
    }

    // 获取校区列表
    const fetchCampusList = async () => {
        try {
            console.log('===== 开始获取校区列表 =====')
            const response = await request.get('/campus/list')
            console.log('校区列表响应:', response)
            campusList.value = response.data?.data || []
            console.log('校区列表数据:', campusList.value)
            return campusList.value
        } catch (error) {
            console.error('获取校区列表失败:', error)
            campusList.value = []
            return []
        }
    }

    // 新增学生
    const addStudent = async () => {
        try {
            console.log('===== 开始新增学生 =====')
            const submitData = { ...formData }

            if (!isSuperAdmin.value && userStore.user?.campus?.id) {
                submitData.campusId = userStore.user.campus.id
                console.log('自动填充校区ID:', submitData.campusId)
            }

            console.log('新增学生数据:', submitData)
            const response = await request.post('/user/students', submitData)
            ElMessage.success('新增学生成功')
            console.log('新增成功响应:', response)
            await fetchStudentList()
            return response.data
        } catch (error) {
            console.error('新增学生失败:', error)
            ElMessage.error('新增学生失败，请重试')
            throw error
        }
    }

    // 更新学生信息
    const updateStudent = async () => {
        try {
            console.log('===== 开始更新学生 =====')
            const submitData = { ...formData }
            console.log('更新学生数据:', submitData)

            const response = await request.put(`/user/students/${submitData.id}`, submitData)
            ElMessage.success('更新学生信息成功')
            console.log('更新成功响应:', response)
            await fetchStudentList()
            return response.data
        } catch (error) {
            console.error('更新学生失败:', error)
            ElMessage.error('更新学生失败，请重试')
            throw error
        }
    }

    // 删除学生
    const deleteStudent = async (studentId) => {
        try {
            console.log('===== 开始删除学生 =====')
            console.log('删除学生ID:', studentId)
            await request.delete(`/user/students/${studentId}`)
            ElMessage.success('删除成功')
            console.log('删除成功')
            await fetchStudentList()
            return true
        } catch (error) {
            console.error('删除学生失败:', error)
            ElMessage.error('删除失败，请重试')
            return false
        }
    }

    // 根据ID获取学生详情
    const getStudentById = async (id) => {
        try {
            console.log('===== 获取学生详情 =====')
            console.log('学生ID:', id)
            const response = await request.get(`/user/students/${id}`)
            console.log('学生详情响应:', response)
            return response.data || null
        } catch (error) {
            console.error(`获取ID为${id}的学生详情失败:`, error)
            return null
        }
    }

    // 重置表单数据
    const resetFormData = (isAdd = true, student = null) => {
        console.log('===== 重置表单数据 =====')
        console.log('操作类型:', isAdd ? '新增' : '编辑')

        if (isAdd) {
            Object.assign(formData, {
                id: null,
                username: '',
                realName: '',
                gender: 'male',
                phone: '',
                email: '',
                age: null,
                campusId: isSuperAdmin.value ? '' : (userStore.user?.campus?.id || ''),
                campusName: ''
            })
        } else if (student) {
            Object.assign(formData, {
                id: student.id,
                username: student.username,
                realName: student.realName,
                gender: student.gender || 'male',
                phone: student.phone || '',
                email: student.email || '',
                age: student.age || null,
                campusId: student.campusId?.id || '',
                campusName: student.campusId?.name || ''
            })
        }
        console.log('重置后表单数据:', formData)
    }

    // 分页参数修改
    const setPageParams = async (page, size) => {
        console.log('===== 修改分页参数 =====')
        console.log('新页码:', page, '新每页条数:', size)
        currentPage.value = page
        pageSize.value = size
        return fetchStudentList()
    }

    // 搜索条件修改
    const setSearchName = (name) => {
        console.log('===== 修改搜索条件 =====')
        console.log('搜索关键词:', name)
        searchName.value = name
        currentPage.value = 1
        return fetchStudentList()
    }

    // 导出状态和方法
    return {
        studentList, total, currentPage, pageSize, loading,
        searchName, campusList, formData, isSuperAdmin,
        fetchStudentList, fetchCampusList, addStudent,
        updateStudent, deleteStudent, getStudentById,
        resetFormData, setPageParams, setSearchName
    }
})
